package controllers

import (
	"fmt"
	"reflect"
	"strings"
	"xdkaika/libs/http"
	"xdkaika/libs/jwt"
	"xdkaika/models"

	"github.com/beego/beego/v2/core/logs"
	beego "github.com/beego/beego/v2/server/web"
)

type BaseController struct {
	beego.Controller
	models.UserProfile // User profile
}

// 验证过滤，并赋值 c.UserProfile
func (c *BaseController) Prepare() {

	//验证token和过滤url
	c.UserProfile = models.UserProfile{}
	requestToken := c.Ctx.Request.Header.Get("Authorization")
	tokenString := strings.TrimSpace(requestToken[len("Bearer "):])
	//url免验证 TODO
	urlExclude := [...]string{
		"/v1/auth/login",
		"/v1/auth/logout",
	}
	url := c.Ctx.Request.URL.Path
	checkExclude := false
	for _, u := range urlExclude {
		fmt.Println("url:", u)
		if u == url {
			checkExclude = true
		}
	}
	userProfile, err := jwt.ValidateToken(tokenString)
	fmt.Println(url, checkExclude, userProfile)
	if !checkExclude && userProfile == nil {
		c.ClientError(0, "STATUS_FORBIDDEN", err, http.STATUS_FORBIDDEN)
		return
	}
	// userProfile 赋值
	if userProfile != nil {
		c.UserProfile = *userProfile
	}
}

/**
* 返回成功并正确的数据
 */
func (c *BaseController) SuccessResult(data ...interface{}) {
	if len(data) > 0 && reflect.ValueOf(data[0]).Len() > 0 {
		c.JsonResult(http.STATUS_OK, 0, "", data[0])
	} else {
		c.JsonResult(http.STATUS_OK, 0, "", make(map[string]interface{}))
	}

}

/**
* 返回成功但错误的数据
 */
func (c *BaseController) ErrorResult(errCode int, errMsg string, data ...interface{}) {
	if len(data) > 0 && reflect.ValueOf(data[0]).Len() > 0 {
		c.JsonResult(http.STATUS_OK, errCode, errMsg, data[0])
	} else {
		c.JsonResult(http.STATUS_OK, errCode, errMsg, make(map[string]interface{}))
	}
	logs.Error(data)
}

/**
* 客户端请求错误 Bad Request
 */
func (c *BaseController) ClientError(errCode int, errMsg string, data interface{}, status ...int) {
	resData := make(map[string]interface{})
	if len(status) > 0 && status[0] >= 400 {
		c.JsonResult(status[0], errCode, errMsg, resData)
	} else {
		c.JsonResult(http.STATUS_BAD_REQUEST, errCode, errMsg, resData)
	}
	logs.Error(data)
}

/**
* 服务器错误
 */
func (c *BaseController) ServerError(errCode int, errMsg string, data interface{}, status ...int) {
	resData := make(map[string]interface{})
	if len(status) > 0 && status[0] >= 500 {
		c.JsonResult(status[0], errCode, errMsg, resData)
	} else {
		c.JsonResult(http.STATUS_INTERNAL_SERVER_ERROR, errCode, errMsg, resData)
	}
	logs.Error(errCode, errMsg, data)
}

/**
 * Ajax接口返回Json
 */
func (c *BaseController) JsonResult(status int, errCode int, errMsg string, data interface{}) {

	jsonData := make(map[string]interface{}, 3)
	jsonData["err_code"] = errCode
	jsonData["message"] = errMsg
	jsonData["data"] = data
	c.Data["json"] = jsonData
	c.Ctx.Output.SetStatus(status)
	c.ServeJSON()
}
